﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using AutoMapper;

using Revis.VClinicNet.Core.Domain;
using Revis.VClinicNet.Core.Domain.Repository;
using Revis.VClinicNet.Core.Domain.Credentials;
using Revis.VClinicNet.App.Internal.Dto;
using Revis.VClinicNet.App.Internal.Dto.Validation;


namespace Revis.VClinicNet.App.Internal.ServiceImpl
{
    public class PatientUserService : IPatientUserService
    {
        protected IPasswordEncrypter _encrypter = null;
        protected IPatientRepository _patientRepository = null;
        protected IPatientUserRepository _patientUserRepository = null;

        public PatientUserService(IPatientRepository ipr, IPatientUserRepository ipur, IPasswordEncrypter encrypter)
        {
            _patientRepository = ipr;
            _patientUserRepository = ipur;
            _encrypter = encrypter;
        }

        public PatientUserActiveDto Activate(long patientId)
        {
            PatientUser user = _patientUserRepository.FindByPatientId(patientId);
            if (user == null) {
                return null;
            }
            string password = Guid.NewGuid().ToString();
            user.SetActive();
            user.SetPassword(_encrypter.Encrypt(password));

            _patientUserRepository.Store(user);

            PatientUserActiveDto dto = Mapper.Map<PatientUser, PatientUserActiveDto>(user);
            dto.Password = password;
            return dto;
        }

        public PatientUserInfoDto Deactivate(long patientId)
        {
            PatientUser user = _patientUserRepository.FindByPatientId(patientId);
            if (user == null) {
                return null;
            }
            user.SetInactive();
            _patientUserRepository.Store(user);
            PatientUserInfoDto dto = Mapper.Map<PatientUser, PatientUserInfoDto>(user);
            return dto;
        }


        public PatientUserActiveDto Reset(long patientId)
        {
            return Activate(patientId);
        }

        public PatientUserInfoDto FindUser(long patientId)
        {
            PatientUser user = _patientUserRepository.FindByPatientId(patientId);
            return Mapper.Map<PatientUser, PatientUserInfoDto>(user);
        }
    }
}
